package tjs.study.notes.dotest.mongo.service;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import tjs.study.notes.dotest.mongo.ClientA;

/**
 * Created by Nicky.Tang on 2021/12/9 9:32 下午
 *
 * @since 02.12.10
 */
@Service
public class UserMongoService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserMongoMapper userMongoMapper;


    public void test脏读() {
        String id = "61b209959f4ab75fda719d16";

        UserMongo userMongo = userMongoMapper.find(id);
        System.out.println("before: " + userMongo.getAmount());

        new Thread(() -> {
            userMongoMapper.addAmount("61b209959f4ab75fda719d16", 10, 1500l, false);
        }).start();

        for (int i = 0; i < 5; i++) {
            userMongo = userMongoMapper.find(id);
            System.out.println(i + "after: " + userMongo.getAmount());
            ClientA.sleep(500l);
        }
    }

    public void test不可重复读() {
        long before = userMongoMapper.count(10);
        System.out.println("before: " + before);

        new Thread(() -> {
            UserMongo userMongo = new UserMongo();
            userMongo.setId(new ObjectId().toString());
            userMongo.setAmount(10);
            userMongoMapper.save(userMongo, 1500l);
        }).start();

        userMongoMapper.countFor(6, 10);

        long last = userMongoMapper.count(10);
        System.out.println("last: " + last);
    }

    public void test幻读() {
        long before = userMongoMapper.count(10);
        System.out.println("before: " + before);

        String id = new ObjectId().toString();
        //String id = "61b49d88e7369110097cd2ff";
        System.out.println(id);
        new Thread(() -> {
            UserMongo userMongo = new UserMongo();
            userMongo.setId(id);
            userMongo.setAmount(10);
            userMongoMapper.save(userMongo, 2600l);

            //userMongoMapper.remove(id, 2600l);//删除这种情况，会无法提交事务报错
        }).start();

        userMongoMapper.countForZ(6, 10, id);

        long last = userMongoMapper.count(10);
        System.out.println("last: " + last);
    }
}
